package com.ruix.app.ui.stratum.notice;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.ruix.app.R;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ActionMapper;
import com.ruix.app.mapper.NoticeDetailMapper;
import com.ruix.app.mapper.SendCommentMapper;
import com.ruix.app.model.Comment;
import com.ruix.app.model.Notice;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.adapter.NoticeDetailCommentAdapter;
import com.ruix.app.ui.adapter.NoticeDetailListAdapter;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.PhotoView;
import com.ruix.app.util.RegUtil;
import com.ruix.app.util.RoleUtil;
import com.ruix.app.util.SoftInputUtil;
import com.ruix.app.widget.CommonTitleBar;
import com.ruix.app.widget.NoticeContentView;
import com.ruix.app.widget.dialog.CopyCommentDialog;
import com.ruix.app.widget.dialog.DeleteNoticeCommentDialog;
import com.ruix.app.widget.linearlistview.LinearListView;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.disposables.Disposable;
import me.iwf.photopicker.PhotoPreview;

/**
 * Created by hadexs on 2017/4/21.
 */

public class NoticeDetailActivity extends BaseActivity implements View.OnClickListener ,DeleteNoticeCommentDialog.DeleteCommentListener {


    public static Intent newIntent(Context context, Notice notice) {
        Intent intent = new Intent(context, NoticeDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("notice", notice);
        intent.putExtras(bundle);
        return intent;
    }

    private Notice notice;

    private TextView noticeTitle, noticeTime, noticeForm, noticeUnconfirm ,sendMessageView;
    private EditText leaveWordsView;
    private ListView listView;//,recyclerViewComments;
//    private NoticeDetailPhotoAdapter adapter;
    private DeleteNoticeCommentDialog deleteCommentDialog;
    private CopyCommentDialog copyCommentDialog;

    private NoticeDetailListAdapter listAdapter;
    private NoticeDetailCommentAdapter commentAdapter;
    private LinearListView commentsView;
    private NoticeContentView noticeContent;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_notice_detail;

    }

    @Override
    protected void initView() {
        setTitle("通知详情");
        sendMessageView = (TextView) findViewById(R.id.tv_send_message);
        leaveWordsView = (EditText) findViewById(R.id.et_leave_words);
        listView = (ListView) findViewById(R.id.recycler_view_notice_photo);
//        recyclerViewComments = (RecyclerView) findViewById(R.id.recycler_view_notice_comment);
        addHeaderView();
        addFooterView();
//        adapter = new NoticeDetailPhotoAdapter(this);


    }

    private void addHeaderView(){
        View headerView = View.inflate(this,R.layout.layout_notice_detail_header,null);
        noticeTitle = (TextView) headerView.findViewById(R.id.tv_notice_title);
        noticeTime = (TextView) headerView.findViewById(R.id.tv_notice_time);
        noticeForm = (TextView) headerView.findViewById(R.id.tv_notice_form);
        noticeUnconfirm = (TextView) headerView.findViewById(R.id.tv_notice_unconfirm);
        noticeContent = (NoticeContentView) headerView.findViewById(R.id.tv_notice_content);
//        headerView.setClickable(false);
        listView.addHeaderView(headerView,null,false);
    }



    private void addFooterView(){
        View footerView = View.inflate(this,R.layout.layout_notice_detail_footer,null);
        commentsView = (LinearListView) footerView.findViewById(R.id.llv_comments_details);
        commentAdapter = new NoticeDetailCommentAdapter(this);
        commentsView.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                Comment comment = notice.getComments().get(position);
                String uid = UserManager.getCurrentUser().getID();
                if (comment.getAuthorId().equals(uid)) {
                    showDeleteCommentDialog(comment,position);
                } else {
                    showCopyCommentDialog(comment.getContent());
                }
            }

            @Override
            public void onItemLongClick(LinearListView parent, View view, int position, long id) {
                Comment comment = notice.getComments().get(position);
                String uid = UserManager.getCurrentUser().getID();
                if (comment.getAuthorId().equals(uid)) {
                    showDeleteCommentDialog(comment,position);
                } else {
                    showCopyCommentDialog(comment.getContent());
                }
            }
        });


        commentsView.setAdapter(commentAdapter);
        listView.addFooterView(footerView,null,false);
    }



    private void initViewValue() {
        if (notice != null) {
            noticeTitle.setText(notice.getTitle());
//            noticeContent.setText(notice.getContent());
            noticeContent.setContentText(notice.getContent());

            //展示时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            Date d1 = new Date(notice.getCeratedTime());
            String displayCreatedTime = format.format(d1);
            noticeTime.setText(displayCreatedTime);

            String roleName = RoleUtil.roleDisplayValue(notice.getRoleID());
            if (!TextUtils.isEmpty(roleName)){
                roleName = String.format("来自于 %s",roleName);
                noticeForm.setText(roleName);
            }
            initConfirmNum(); //

            //确认通知
            String uid = UserManager.getCurrentUser().getID();
            if (!notice.getAuthorid().equals(uid)) {
                if (notice.isNeedConfirm() && !notice.isConfirmed()) {
                    CommonTitleBar titleBar = getTitleBar();
                    TextView titleBarRightBtn = titleBar.getRightBtn();
                    titleBarRightBtn.setText("确认通知");
                    titleBarRightBtn.setTextColor(getResources().getColor(R.color.green));
                    titleBarRightBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            confirmNotice();
                        }
                    });
                }
            }

            listAdapter = new NoticeDetailListAdapter(notice,this);
            listView.setAdapter(listAdapter);
        }
    }

    private void initConfirmNum(){
        String uid = UserManager.getCurrentUser().getID();
        if (notice.getAuthorid().equals(uid)){
            if (notice.getMemberNum() -1  > notice.getConfirmNum()) {
                noticeUnconfirm.setEnabled(true);
                noticeUnconfirm.setTextColor(getResources().getColor(R.color.green));
            } else {
                noticeUnconfirm.setTextColor(getResources().getColor(R.color.gray));
                noticeUnconfirm.setEnabled(false);
            }
            String cofirmCount = String.format("%d/%d确认", notice.getConfirmNum(), notice.getMemberNum());
            noticeUnconfirm.setText(cofirmCount);
            noticeUnconfirm.setVisibility(View.VISIBLE);
        } else {
            noticeUnconfirm.setVisibility(View.GONE);
        }

    }

    private void hideConfirmNoticeButtom(){
        CommonTitleBar titleBar = getTitleBar();
        TextView titleBarRightBtn = titleBar.getRightBtn();
        titleBarRightBtn.setVisibility(View.GONE);
    }

    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null) {
            notice = (Notice) intent.getSerializableExtra("notice");
        }
        initViewValue();
        loadNoticeDetail();
    }

    @Override
    protected void initListener() {
        leaveWordsView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    SoftInputUtil.hideSoftInput(leaveWordsView);
                    submitComment();
                    return true;
                }
                return false;
            }
        });

        leaveWordsView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0){
                    sendMessageView.setEnabled(true);
                    sendMessageView.setBackgroundResource(R.drawable.shape_login_btn_bg);
                } else {
                    sendMessageView.setEnabled(false);
                    sendMessageView.setBackgroundResource(R.drawable.shape_login_btn_bg_disable);
                }
            }
        });

        noticeUnconfirm.setOnClickListener(this);
        sendMessageView.setOnClickListener(this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (notice.getAlbum() != null && notice.getAlbum().size() > 0) {
                    PhotoView.builder()
                            .setPhotos(notice.getAlbum())
                            .setCurrentItem(position - 1)
                            .start(NoticeDetailActivity.this);

//                    PhotoPreview.builder()
//                            .setPhotos(notice.getAlbum())
//                            .setCurrentItem(position - 1)
//                            .setShowDeleteButton(false)
//                            .start(NoticeDetailActivity.this);
                }
            }
        });


    }

//    private void

    //确认通知
    private void confirmNotice() {
        showLoading();
        RequestFactory.confirmNotice(notice.getId(), null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                showSuccessTip("确认成功");
                hideConfirmNoticeButtom();
                notice.setConfirmNum(notice.getConfirmNum() + 1);
                initConfirmNum();
                sendNeedupdateNotice();
                //
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });
    }


    public void submitComment() {
        String comment = leaveWordsView.getText().toString().trim();
        if (TextUtils.isEmpty(comment)){
            showErrorTip("输入留言、输入限制300字");
            return;
        }

        if (comment.length() > 300){
            showErrorTip("留言只能输入300字");
            return;
        }



        showLoading();
        RequestFactory.sendNoticeComment(notice.getId(), comment, new SendCommentMapper(), new RXObserver<Comment>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Comment value) {
                notice.addComment(value);
                commentAdapter.replaceAll(notice.getComments());
                leaveWordsView.setText("");
                SoftInputUtil.hideSoftInput(leaveWordsView);
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });

    }

    private void loadNoticeDetail() {
        RequestFactory.noticeDetail(notice.getId(), new NoticeDetailMapper(), new RXObserver<Notice>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Notice value) {
                if (value != null && value.getId().equals(notice.getId())) {
                    notice.setComments(value.getComments());
                    //TODO 显示评论
                    commentAdapter.replaceAll(notice.getComments());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_notice_unconfirm:
                startActivity(ConfirmPersonActivity.newIntent(this, notice));
                break;

            case R.id.tv_send_message:
                submitComment();
                break;
        }
    }

    private void showDeleteCommentDialog(Comment comment, int commentPosition){
        if (deleteCommentDialog == null) {
            deleteCommentDialog = new DeleteNoticeCommentDialog(this);
            deleteCommentDialog.setListener(this);
        }
        deleteCommentDialog.show(comment,commentPosition);
    }

    private void showCopyCommentDialog(String comment){
        if (copyCommentDialog == null) {
            copyCommentDialog = new CopyCommentDialog(this);
        }
        copyCommentDialog.show(comment);
    }


    private void deleteSelfComment(Comment comment,final int position){
        showLoading();
        RequestFactory.deleteNoticeComment(comment.getID(),new ActionMapper(), new RXObserver<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean value) {
                if (value){
                    showSuccessTip("删除成功");
                    notice.removeCommentWithiPosition(position);
                    commentAdapter.remove(position);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });

    }

    @Override
    public void deleteCommentPositive(int commentPosition) {
        Comment comment = notice.getComments().get(commentPosition);
        deleteSelfComment(comment,commentPosition);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (listAdapter != null) {
            listAdapter.relesae();
        }
        copyCommentDialog = null;
        deleteCommentDialog = null;
    }

    private void sendNeedupdateNotice(){
        Intent intent = new Intent();
        intent.setAction(RuiXConstant.NOTICE_UPDATE_NOTICE_LIST);
        sendOrderedBroadcast(intent,null);
    }
}
